package com.md.youyouhui.ui.shopping;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.md.youyouhui.R;
import com.md.youyouhui.databinding.ActivityShoppingAddressBinding;
import com.md.youyouhui.net.Constants;
import com.md.youyouhui.net.response.GetAddressResponse;
import com.md.youyouhui.net.response.WxPayResponse;
import com.md.youyouhui.ui.BaseActivity;
import com.md.youyouhui.ui.pay.AuthResult;
import com.md.youyouhui.ui.pay.PayResult;
import com.md.youyouhui.utils.ToastUtils;
import com.md.youyouhui.view.MainViewModel;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.Map;

/**
 * Created by AdministratorZJ
 * on 2019/5/23.
 */
public class ShoppingAddressActivity extends BaseActivity {
    private ActivityShoppingAddressBinding addressBinding;
    private String phone, name, area, minute, code, addressId;
    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;
    private MainViewModel viewModel;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(ct, "支付成功", Toast.LENGTH_SHORT).show();
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(ct, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        // 获取alipay_open_id，调支付时作为参数extern_token 的value
                        // 传入，则支付账户为该授权账户
                        Toast.makeText(ct, "授权成功", Toast.LENGTH_SHORT).show();
                    } else {
                        // 其他状态值则为授权失败
                        Toast.makeText(ct, "授权失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };
    private String id;
    private IWXAPI msgApi;

    @Override
    public void setContentLayout() {
        addressBinding = DataBindingUtil.setContentView(this, R.layout.activity_shopping_address);
        viewModel = new MainViewModel();
    }

    @Override
    public void initView() {
        setSupportActionBar(addressBinding.toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public void initData() {
        msgApi = WXAPIFactory.createWXAPI(this,Constants.WXKEY,false );
        // 将该app注册到微信
        msgApi.registerApp(Constants.WXKEY);
        String price = getIntent().getStringExtra("price");
        id = getIntent().getStringExtra("id");
        addressBinding.payAllPrice.setText(String.format("¥%s", price));
        addressBinding.address.setOnClickListener(v -> startActivityForResult(new Intent(ct, AddressMangerActivity.class), 100));
        addressBinding.pay.setOnClickListener(v -> {
            if (TextUtils.isEmpty(addressId)) {
                Toast.makeText(ct, "请添加收货地址", Toast.LENGTH_SHORT).show();
                return;
            }
            showPayDialog();
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        //选择了其他地址，就不使用默认地址
        if (TextUtils.isEmpty(name)) {
            getDefault();
        }
    }

    private void getDefault() {
        viewModel.getDefaultAddress().observe(this, getAddressResponse -> {
            assert getAddressResponse != null;
            switch (getAddressResponse.status) {
                case LOADING:
                    addressBinding.progress.setVisibility(View.VISIBLE);
                    break;
                case SUCCESS:
                    addressBinding.progress.setVisibility(View.GONE);
                    GetAddressResponse data = getAddressResponse.data;
                    if (null == data) {
                        return;
                    }
                    if (TextUtils.isEmpty(data.mobilePhone)) {
                        addressBinding.addressName.setText("请添加收货地址");
                        addressBinding.addressAdd.setVisibility(View.GONE);
                    } else {
                        addressId = data.id;
                        addressBinding.addressName.setText(String.format("%s\t\t\t%s", data.consignee, data.mobilePhone));
                        addressBinding.addressAdd.setVisibility(View.VISIBLE);
                        addressBinding.addressAdd.setText(String.format("%s%s", data.area, data.detailedAddress));
                    }
                    break;
                case ERROR:
                    addressBinding.progress.setVisibility(View.GONE);
                    ToastUtils.errMake(this, getAddressResponse.errorCode);
                    break;
                default:
                    break;
            }
        });
    }

    private void showPayDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_pay, null);
        builder.setView(view);
        builder.setMessage("请选择支付方式");
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
        ConstraintLayout aliPay = view.findViewById(R.id.aliPay);
        ConstraintLayout wxPay = view.findViewById(R.id.wxPay);
        aliPay.setOnClickListener(v -> {
            payMoneyCard();
            alertDialog.dismiss();
        });
        wxPay.setOnClickListener(v -> {
            //Toast.makeText(this, "敬请期待", Toast.LENGTH_SHORT).show();
            wxPayService();
            alertDialog.dismiss();
        });
    }

    private void wxPayService() {
        viewModel.shoppingPay(id, addressId, "1").observe(this, objectResource -> {
            assert objectResource != null;
            switch (objectResource.status) {
                case SUCCESS:
                    Map<String, String> jsonObject = (Map<String, String>) objectResource.data;
                    if (null == jsonObject) {
                        Toast.makeText(ct, "获取支付wx_orderInfo为null", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    Log.e("paymsg",jsonObject.toString());
                    String appid = jsonObject.get("appid");
                    String partnerid = jsonObject.get("partnerid");
                    String prepayid = jsonObject.get("prepayid");
                    String packageValue = jsonObject.get("package");
                    String noncestr = jsonObject.get("noncestr");
                    String timestamp = jsonObject.get("timestamp");
                    String sign = jsonObject.get("sign");
                    WxPayResponse wxPayResponse = new WxPayResponse();
                    wxPayResponse.appid = appid;

                    wxPayResponse.partnerid = partnerid;
                    wxPayResponse.prepayid = prepayid;
                    wxPayResponse.packageValue = packageValue;
                    wxPayResponse.noncestr = noncestr;
                    wxPayResponse.timestamp = timestamp;
                    wxPayResponse.sign = sign;
                    wxAli(wxPayResponse);
                    break;
                case ERROR:
                    ToastUtils.errMake(activity, objectResource.errorCode);
                    break;
                default:
                    break;
            }
        });
    }

    private void wxAli(WxPayResponse data) {
        PayReq request = new PayReq();
        request.appId = data.appid;

        request.partnerId = data.partnerid;
        request.prepayId = data.prepayid;
        request.packageValue = data.packageValue;
        request.nonceStr = data.noncestr;
        request.timeStamp = data.timestamp;
        request.sign = data.sign;
        msgApi.registerApp( Constants.WXKEY );
        msgApi.sendReq(request);
    }

    private void payMoneyCard() {
        viewModel.shoppingPay(id, addressId, "0").observe(this, objectResource -> {
            assert objectResource != null;
            switch (objectResource.status) {
                case SUCCESS:
                    String data = (String) objectResource.data;
                    if (TextUtils.isEmpty(data)) {
                        Toast.makeText(ct, "获取支付orderInfo为null", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    payAli(data);
                    break;
                case ERROR:
                    ToastUtils.errMake(activity, objectResource.errorCode);
                    break;
                default:
                    break;
            }
        });
    }

    private void payAli(String orderInfo) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(ShoppingAddressActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == RESULT_OK) {
            if (null == data) {
                return;
            }
            Bundle extras = data.getExtras();
            if (extras == null) {
                return;
            }
            GetAddressResponse address = (GetAddressResponse) extras.getSerializable("address");
            if (null == address) {
                return;
            }
            name = address.consignee;
            phone = address.mobilePhone;
            area = address.area;
            minute = address.detailedAddress;
            code = address.postcode;
            addressId = address.id;
            addressBinding.addressName.setText(String.format("%s\t\t\t%s", name, phone));
            addressBinding.addressAdd.setVisibility(View.VISIBLE);
            addressBinding.addressAdd.setText(String.format("%s%s", area, minute));
        }
    }
}
